package com.huyun.web.concurrency.blocking;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * @author huyunqiang
 * @Date 2020/1/7 19:02
 */

public class ArrayBlockingQueueDemo {
    /*
     * 一个由数组结构组成的有界阻塞队列
     * 特点：
     *   取出阻塞队列中的值 先进先出
     *   如果队列满了阻塞在外面的线程对队列访问的顺序是不能保证线程公平的
     *
     */
    public static void main(String[] args) {
        BlockingQueue<String> blockingQueue = new ArrayBlockingQueue(3);

        new Thread(new Runnable(){

            @Override
            public void run() {
                try {
                    System.out.println(Thread.currentThread().getName()+"put  1 ") ;
                    blockingQueue.put("1");

                    System.out.println(Thread.currentThread().getName()+"put  2") ;
                    blockingQueue.put("2");

                    System.out.println(Thread.currentThread().getName()+"put  3 ") ;
                    blockingQueue.put("3");

                    System.out.println(Thread.currentThread().getName()+"put  4 ") ;
                    blockingQueue.put("4");

                    System.out.println(Thread.currentThread().getName()+"put  5 ") ;
                    blockingQueue.put("5");
                    System.out.println(Thread.currentThread().getName()+"put  6 ") ;
                    blockingQueue.put("6");
                    System.out.println(Thread.currentThread().getName()+"put  7 ") ;
                    blockingQueue.put("7");
                    System.out.println(Thread.currentThread().getName()+"put  8 ") ;
                    blockingQueue.put("8");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"AAAA").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //取出阻塞队列中的值 先进先出
                    System.out.println(Thread.currentThread().getName()+"-"+blockingQueue.take());
                    System.out.println(Thread.currentThread().getName()+"-"+ blockingQueue.take());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"BBB").start();
    }
}
